﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SqliteORM;

//TODO - fix namepaces. 
namespace TwKarma.Data.Entity
{
    [Table]
	public class Setting : TableBase
	{
        public enum Key
        {
            LastSearchResult = 1001,
            LastSearchResultId = 1002
        }

        [PrimaryKey]
        public int KeyId { get; set; }

		[Field(Size=1000)]
		public string Value { get; set; }

        public static string Get(Key key)
        {
            using (TableAdapter<Setting> adapter = TableAdapter<Setting>.Open())
            {
                Setting s = adapter.ReadAll(Where.Equal("KeyId", key)).FirstOrDefault();
                if (s == null)
                    return null;

                return s.Value;
            }
        }

        public static T Get<T>(Key key, Func<string, T> parse, T @default) 
        {
            using (TableAdapter<Setting> adapter = TableAdapter<Setting>.Open())
            {
                Setting s = adapter.ReadAll(Where.Equal("KeyId", key)).FirstOrDefault();
                if (s == null)
                    return @default;

                return parse(s.Value);
            }
        }

        public static void Set(Key key, string value)
        {
            using (TableAdapter<Setting> adapter = TableAdapter<Setting>.Open())
            {
                adapter.CreateUpdate(key, value);
            }
        }
	}
}